/*
 * @Descripttion: 
 * @version: 
 * @Author: xuyang
 * @Date: 2021-05-17 21:30:11
 * @LastEditors: xuyang
 * @LastEditTime: 2021-05-18 00:03:30
 */
/*
 * @Author: XuYang
 * @Date: 2021-05-06 17:19:40
 * @Last Modified by: XuYang
 * @Last Modified time: 2021-05-17 17:43:58
 * 中间件, 判断token是否存在, 是否生效.
 */
import { App, Provide } from '@midwayjs/decorator';
import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { Context, Application } from 'egg';
import * as jwt from 'jsonwebtoken';
@Provide()
export class jwtTokenHandle implements IWebMiddleware {
    @App()
    app: Application;

    resolve() {
        return async (ctx: Context, next: IMidwayWebNext) => {
            const token = ctx.headers.authorization;
            console.log('token:' + token)
            if(
              this.app.config.jwtTokenHandle.allowed.indexOf(ctx.request.path) >= 0
              || ctx.request.path.indexOf('/public') >= 0
            ) {
              await next();
              return;
            } else {
                let decode: any;
                if (token) {
                    try {
                      // 解码token
                      decode = jwt.verify(token, this.app.config.jwt.secret);
                      const nowTime = new Date().getTime() / 1000;
                      if(nowTime > decode.exp){
                        // 过期
                        ctx.body = {
                          code: 1001,
                          message: 'token已过期'
                        }
                      }else {
                        //刷新cookies
                        // const token = jwt.sign({name: decode.name}, this.app.config.jwt.secret, { expiresIn: this.app.config.jwt.expiresIn })
                        // console.log('refToken', token)
                        // ctx.cookies.set('token', token);
                        return await next();
                      }
                    } catch (error) {
                      if(error.name === 'TokenExpiredError'){
                        ctx.body = {
                          code: 1001,
                          message: 'token已过期'
                        }
                      }else {
                        ctx.body = {
                          code: -1,
                          message: error.message
                        }
                      }
                    }
                } else {
                  ctx.body = {
                    code: -101,
                    message: '没有token，请登录后再操作',
                  };
                  return;
                }
            }
        };
    }
}
